package cn.xiaobai.listener;

import cn.xiaobai.domain.ExcelData;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 表格导入监听器
 *
 * @Author yangdaji
 * @Date 2024/3/23
 * @PackageName cn.xiaobai.listener
 * @ClassName ExcelImportListener
 */
public class ExcelImportListener implements ReadListener<Object> {

    private final ExcelData excelData = new ExcelData();

    private List<List<Object>> body = new ArrayList<>();

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        List<String> headList = headMap.values().stream().map(ReadCellData::getStringValue).toList();
        excelData.setHead(headList);
    }

    @Override
    public void invoke(Object data, AnalysisContext context) {
        if (data instanceof LinkedHashMap) {
            LinkedHashMap dataMap = (LinkedHashMap) data;
            List<Object> dataList = new ArrayList<>();
            dataMap.keySet().forEach(k -> {
                dataList.add(dataMap.get(k));
            });
            body.add(dataList);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        excelData.setBody(body);
    }

    public ExcelData getExcelData() {
        return excelData;
    }
}
